package com.jishuo.nontax.bfc.service;


import com.github.pagehelper.PageHelper;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.Pagination;
import com.jishuo.base.bean.vo.UserVO;
import com.jishuo.base.config.NonTaxConfig;
import com.jishuo.base.dao.UserMapper;
import com.jishuo.base.service.SequenceService;
import com.jishuo.base.util.ExportSXSSFUtil;
import com.jishuo.base.util.MD5;
import com.jishuo.nontax.bean.bank.Bank;
import com.jishuo.nontax.bean.bank.IllegalactivityDetail;
import com.jishuo.nontax.bean.bank.Illegalactivityinfo;
import com.jishuo.nontax.bean.bank.OnlineOrder;
import com.jishuo.nontax.bean.message.SetIllegalactivityCrossPayInfo;
import com.jishuo.nontax.bean.message.SetIllegalactivityinfo;
import com.jishuo.nontax.bean.vo.BankStationVO;
import com.jishuo.nontax.bean.vo.BankVO;
import com.jishuo.nontax.bean.vo.IllegalactivityDetailVO;
import com.jishuo.nontax.bean.vo.IllegalactivityinfoVO;
import com.jishuo.nontax.bfc.dao.*;
import com.jishuo.nontax.bfc.pzk.PzkService;
import com.jishuo.nontax.bfc.tlq.MessageFactory;
import com.jishuo.nontax.bfc.tlq.MessageService;
import com.jishuo.nontax.util.BillStateUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @auther dinggaofei
 * @Date 2022/12/23 9:25
 */
@Service
public class IllegalactivityinfoService {

    private static Logger logger = LoggerFactory.getLogger(IllegalactivityinfoService.class);
    @Resource
    private IllegalactivityinfoMapper illegalactivityinfoMapper;
    @Resource
    private IllegalactivityDetailMapper illegalactivityDetailMapper;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private MessageService messageService;
    @Resource
    private NonTaxConfig nonTaxConfig;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private ChargeBillMapper chargeBillMapper;
    @Resource
    private BaseDataMapper baseDataMapper;


    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * @param billnum 单据号
     * @auther dinggaofei
     * @Date 2022/12/23 10:02
     * @description 获取交管处罚决定书单据
     */
    public BaseResult getIllegalactivityInfo(String billnum) {
        //根据票据号从本地查询交管处罚决定书单据
        IllegalactivityinfoVO info = illegalactivityinfoMapper.findIllegalactivityInfo(billnum);

        try {
            BaseResult result = new BaseResult();

            //已缴费的直接返回
            if (info != null && info.getBillstate() == 3) {
                info.setBillstate(3);
                result.setData(info);
                result.setMsgExt(BillStateUtil.getBillState(BillStateUtil.BillType_Illegal, info.getBillstate()));
                return result;
            }
            //更新messageid
            Long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            if (info == null) {
                long iaiid = sequenceService.getNextSeq("JJILLEGALACTIVITYINFOSEQ");
                info = new IllegalactivityinfoVO();
                info.setMessageid(messageid);
                info.setIaiid(iaiid);
                info.setBillnum(billnum);
                illegalactivityinfoMapper.insertBlankIllegalacInfo(info);
            } else {
                info.setMessageid(messageid);
                illegalactivityinfoMapper.updateMsgIllegalacInfo(info);
            }
            //从财政查询
            boolean suc = messageService.sendAndRecvMessage("GETILLEGALACTIVITYINFO", messageid, MessageFactory.getIllegalactivityInfo(billnum), "2.0");
            if (suc) {
                info = illegalactivityinfoMapper.findIllegalactivityInfo(billnum);
                info.setDetailVOS(illegalactivityDetailMapper.findDetail(billnum));
                result.setData(info);
                result.setMsgExt(BillStateUtil.getBillState(BillStateUtil.BillType_Illegal, info.getBillstate()));
                return result;
            }
            return new BaseResult(ErrorCodeEnum.BILL_GET_TIMEOUT);
        } catch (Exception e) {
            logger.info("失败：" + e);
            return null;
        }
    }


    /**
     * @param billnum        决定书编号
     * @param specialbillnum 专用票据编号
     * @auther dinggaofei
     * @Date 2022/12/23 13:32
     * @description 修改交管处罚决定书中的罚没票据号
     */
    public BaseResult setPunishBillnum(String billnum, String specialbillnum) {
        IllegalactivityinfoVO vo = new IllegalactivityinfoVO();
        vo.setBillnum(billnum);
        vo.setBilltypeid(794L);
        vo.setSpecialbillnum(specialbillnum);
        int n = illegalactivityinfoMapper.updateIllegalactivitySpecialbillnum(vo);
        if (n < 1) {
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }

        //发送财政
        try {
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            Object obj = MessageFactory.setPunishBillnum(vo);
            messageService.sendMessage("SETPUNISHBILLNUM", messageid, obj, "2.0");
        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.TLQ_ERR);
        }
        return new BaseResult();
    }


    /**
     * billnum
     *
     * @auther dinggaofei
     * @Date 2022/12/26 11:50
     * @description 记录跨省收款信息，将业务数据进行加密发送给财政；并将缴款书标示为已收款。   交管处罚决定书单据跨省收款
     */
    public BaseResult setIllegalactivityCrossPayInfo(IllegalactivityinfoVO payinfo) {
        //添加数据验证
        String errnum = "";
        if (payinfo.getBillnum() == null || "".equals(payinfo.getBillnum().trim())) {
            errnum = "errnum=2,";
        } else if (payinfo.getPaybankdt() == null || "".equals(payinfo.getPaybankdt().trim())) {
            errnum = "errnum=3,";
        } else if (payinfo.getBankaffirm() == null || "".equals(payinfo.getBankaffirm().trim())) {
            errnum = "errnum=4,";
        } else if (payinfo.getBankstation() == null || "".equals(payinfo.getBankstation().trim())) {
            errnum = "errnum=5,";
        } else if ("".equals(payinfo.getBankid() + "")) {
            errnum = "errnum=6,";
        } else if (payinfo.getTrafficunitnum() == null || "".equals(payinfo.getTrafficunitnum().trim()) && payinfo.getTrafficunitnum().length() >= 6) {
            errnum = "errnum=7,";
        } else if (payinfo.getFunds().compareTo(payinfo.getLatefee()) < 0) {
            errnum = "errnum=8,";
        }
        if (!"".equals(errnum)) {
            logger.info(errnum + "上传跨省交管缴款失败");
            return new BaseResult(ErrorCodeEnum.PARAM_ERR);
        }
        try {
            if (illegalactivityinfoMapper.findIllegInfoCount(payinfo.getBillnum()) > 0) {
                illegalactivityinfoMapper.updateIllegalactivityInfo(payinfo);
            } else {
                long iaiid = sequenceService.getNextSeq("JJILLEGALACTIVITYINFOSEQ");
                payinfo.setIaiid(iaiid);
                illegalactivityinfoMapper.insertIllegalactivityInfo(payinfo);
            }
            //发送财政
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");

            Object obj = MessageFactory.setIllegalactivityCrossPayInfo(payinfo);
            messageService.sendMessage("SETILLEGALACTIVITYCROSSPAYINFO", messageid, obj, "2.0");
            if (nonTaxConfig.IS_Pzk) {
                PzkService.sendPzk("SETILLEGALACTIVITYCROSSPAYINFOPZK", obj);
            }

        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.TLQ_ERR);
        }
        return new BaseResult();
    }

    @Resource
    private OnlineOrderMapper onlineOrderMapper;

    /**
     * @auther dinggaofei
     * @Date 2022/12/26 13:41
     * @description 记录收款信息 , 并将缴款书标示为已收款   交管处罚决定书单据收款
     */
    public BaseResult setPayInfo(IllegalactivityinfoVO infoVOPa) {
        // 判断参数
        String retMsg = "";
        if (String.valueOf(infoVOPa.getPayway()).length() == 1) {
            infoVOPa.setPaywaycode("0" + infoVOPa.getPayway());
        }
        int payWay = chargeBillMapper.findPayWay(infoVOPa.getPaywaycode());
        if (infoVOPa.getBillnum() == null || "".equals(infoVOPa.getBillnum())) {
            retMsg += "票号未填写；";
        } else if (infoVOPa.getPaybankdt() == null || "".equals(infoVOPa.getPaybankdt())) {
            retMsg += "缴费时间未填写；";
        } else if (infoVOPa.getBankaffirm() == null || "".equals(infoVOPa.getBankaffirm())) {
            retMsg += "交易流水号未填写；";
        } else if ("0".equals(String.valueOf(payWay)) || String.valueOf(payWay) == null || "".equals(String.valueOf(payWay))) {
            retMsg += "付款方式未填写；";
        }
        if (!"".equals(retMsg)) {
            logger.info("缴费参数错误。" + retMsg);
            //参数错误
            return new BaseResult(ErrorCodeEnum.PARAM_ERR);
        }
        IllegalactivityinfoVO infoVO = illegalactivityinfoMapper.findIllegalactivityInfo(infoVOPa.getBillnum());
        if (infoVO == null) {
            logger.info("交罚票号不存在：" + infoVO.getBillnum() + "）");
        }
        //判断是否已缴费
        if (Integer.valueOf(1).equals(infoVO.getIsbankaffirm())) {
            //票据已缴费
            return new BaseResult(ErrorCodeEnum.BILL_PAYED);
        }

        BankVO bankVO = bankMapper.findBankVO(infoVO.getAccountcode());

        //更新交罚业务表
        long bankid = bankVO.getBankid();
        long messageid = 0;
        try {
            messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }
        String sendtime = sdf.format(new Date());
        infoVO.setMessageid(messageid);
        infoVO.setSendtime(sendtime);
        infoVO.setBankid(bankid);
        int i = illegalactivityinfoMapper.updateIllegalactivityBankAffirm(infoVO);
        if (i < 1) {
            //更新数据失败
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }
        OnlineOrder oo = new OnlineOrder();
        oo.setBillnum(infoVOPa.getBillnum());
        oo.setAmt(infoVO.getFunds().add(infoVO.getLatefee()).toPlainString());
        oo.setBankaffirm(infoVOPa.getBankaffirm());
        oo.setBilltype(2);
        oo.setPaybankdt(infoVOPa.getPaybankdt());
        oo.setPaychnl(infoVOPa.getPaychnl());
        Bank bank = bankMapper.findBankByBankidIsenable(infoVOPa.getBankid());
        oo.setPayee(bank.getAccountname());
        oo.setPayeeaccount(bank.getAccountcode());
        oo.setPayer(infoVO.getOccurname());
        oo.setPayeraccount(infoVO.getPayeraccount());
        onlineOrderMapper.saveOnlineOrder(oo);
        // 发送财政
        try {
            Object obj = MessageFactory.setPayInfo(infoVO);
            messageService.sendMessage("SETPAYINFO", messageid, obj, "2.0");

            //写凭证
            if (nonTaxConfig.IS_Pzk) {
                PzkService.sendPzk("SETPAYINFOPZK", obj);
            }
        } catch (Exception e) {
            logger.info("交罚缴费失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.TLQ_ERR);
        }
        return new BaseResult();
    }

    public void setIllegalactivityInfo(String data, int billstate, String sn) {
        if (billstate == 1) {
            try {

                //xml解析器  t_jjillegalactivityinfo
                Serializer serializer = new Persister();
                //返回缴款书对象
                SetIllegalactivityinfo ill = serializer.read(SetIllegalactivityinfo.class, new StringReader(data));
                IllegalactivityinfoVO vo = new IllegalactivityinfoVO(ill);
                ArrayList<IllegalactivityDetailVO> detailVOS = vo.getDetailVOS();
                illegalactivityinfoMapper.delIllegalDetail(vo.getBillnum());
                for (IllegalactivityDetailVO detailvo : detailVOS) {
                    illegalactivityinfoMapper.insertIllegalDetail(detailvo);
                }
                vo.setBillstate(billstate);
                vo.setIssend(2);
                vo.setBankid(Long.valueOf(ill.getBankid()));
                if (illegalactivityinfoMapper.findIllegInfoMsgCount(vo.getBillnum()) > 0) {
                    illegalactivityinfoMapper.updateMsgIllegalDetail(vo);
                } else {
                    illegalactivityinfoMapper.insertMsgIllegalDetail(vo);
                }
            } catch (Exception e) {
                logger.info("失败：" + e);
            }
        } else {
            illegalactivityinfoMapper.updateIllegalactivityinfoState(sn, billstate);
        }
    }


    public List<IllegalactivityinfoVO> listIllage(IllegalactivityinfoVO illegalactivityinfoVO, Pagination pagination) {
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return illegalactivityinfoMapper.listIllage(illegalactivityinfoVO);
    }

    public BaseResult saveIllage(IllegalactivityinfoVO illegalactivityinfoVO) {
        int n = illegalactivityinfoMapper.saveIllage(illegalactivityinfoVO);
        if (n < 1) return new BaseResult(ErrorCodeEnum.DB_ERR);
        return new BaseResult();
    }

    public IllegalactivityinfoVO getIllage(Long iaiid) {
        return illegalactivityinfoMapper.getIllage(iaiid);
    }

    @Resource
    private UserMapper userMapper;

    public BaseResult sendIllage(List<String> billids, String userpwd, String usercode) {
        if (userMapper.getUserCount(MD5.md5s(userpwd), usercode) > 0) {
            if (billids != null && billids.size() > 0) {
                List<IllegalactivityinfoVO> illegalactivityinfoVOS = illegalactivityinfoMapper.findIllagelactivityInfo(billids);
                String errnum = "";
                for (IllegalactivityinfoVO infoVO : illegalactivityinfoVOS
                ) {
                    if (infoVO.getIsnohere().equals("2")) {
                        IllegalactivityinfoVO illegalactivityinfoVO = illegalactivityinfoMapper.selectInfo(infoVO.getBillnum());
                        SetIllegalactivityCrossPayInfo payinfo = illegalactivityinfoVO.setIllegalactivityCrossPayInfo();
                        if (payinfo.getBillnum() == null || "".equals(payinfo.getBillnum().trim())) {
                            errnum = "errnum=2,";
                        } else if (payinfo.getPaybankdt() == null || "".equals(payinfo.getPaybankdt().trim())) {
                            errnum = "errnum=3,";
                        } else if (payinfo.getBankaffirm() == null || "".equals(payinfo.getBankaffirm().trim())) {
                            errnum = "errnum=4,";
                        } else if (payinfo.getBankstation() == null || "".equals(payinfo.getBankstation().trim())) {
                            errnum = "errnum=5,";
                        } else if ("".equals(payinfo.getBankid() + "")) {
                            errnum = "errnum=6,";
                        } else if (payinfo.getTrafficunitnum() == null || "".equals(payinfo.getTrafficunitnum().trim()) && payinfo.getTrafficunitnum().length() >= 6) {
                            errnum = "errnum=7,";
                        } else if (payinfo.getFunds().compareTo(payinfo.getLatefee()) < 1) {
                            errnum = "errnum=8,";
                        } else {
                            setIllegalactivityCrossPayInfo(illegalactivityinfoVO);
                        }
                        if ("".equals(errnum)) {
                            return new BaseResult(ErrorCodeEnum.DATA_NOT_FOUND); //数据不存在
                        }
                    } else {
                        return setPayInfo(infoVO);
                    }

                }
            } else {
                return new BaseResult(ErrorCodeEnum.BILL_NOT_FOUND);//单据不存在
            }

        } else {
            return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "用户信息验证失败");
        }
        return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);  //未知错误

    }

    /* public BaseResult cleanIllage(String billid, String userpsw, String usercode) {
         String errinfo = "";
         String errnum = "", errbillnum = "";
         if (userMapper.getUserCount(userpsw, usercode) > 0) {
             if (billid != null && billid != "") {
                 IllegalactivityinfoVO vo = new IllegalactivityinfoVO();
                 vo.setBillid(billid);

             }
         }

         return new BaseResult();

     }*/
//更新收款状态
    public BaseResult updateIllage(List<String> billids, String userpwd, String usercode) {


        if (userMapper.getUserCount(MD5.md5s(userpwd), usercode) > 0) {
            String errnum = "";
            try {
                if (billids != null && billids.size() > 0) {
                    List<IllegalactivityinfoVO> illegalactivityinfoVOS = illegalactivityinfoMapper.findIllagelactivityInfo(billids);
                    for (IllegalactivityinfoVO vo : illegalactivityinfoVOS
                    ) {
                        if (vo.getSendtime().equals("")) {
                            if (vo.getBillnum() == null || "".equals(vo.getBillnum())) {
                                errnum = "errnum=1";
                            } else if (vo.getPaybankdt() == null || "".equals(vo.getPaybankdt())) {
                                errnum = "errnum=2";
                            } else if (vo.getBankaffirm() == null || "".equals(vo.getBankaffirm())) {
                                errnum = "errnum=3";
                            } else if (vo.getBankstation() == null || "".equals(vo.getBankstation())) {
                                errnum = "errnum=4";
                            } else if (vo.getPayway() == null || vo.getPaybankdt().equals("") || vo.getPaybankdt().equals("0")) {
                                errnum = "errnum=5";
                            }
                            if (!"".equals(errnum)) {
                                return new BaseResult(ErrorCodeEnum.PARAM_ERR);
                            } else {
                                setPayInfo(vo);
                                illegalactivityinfoMapper.updateIsbankaffirm(vo.getIaiid());
                            }
                        } else {
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date date2 = sdf.parse(vo.getSendtime());
                            long temp = date.getTime() - date2.getTime();    //相差毫秒数
                            long hours = temp / 1000 / 3600;                //相差小时数
                            long temp2 = temp % (1000 * 3600);
                            long mins = temp2 / 1000 / 60;                    //相差分钟数
                            if (((hours * 60) + mins) < (nonTaxConfig.CxTime)) {
                                if (vo.getBillnum() == null || "".equals(vo.getBillnum())) {
                                    errnum = "errnum=1";
                                } else if (vo.getPaybankdt() == null || "".equals(vo.getPaybankdt())) {
                                    errnum = "errnum=2";
                                } else if (vo.getBankaffirm() == null || "".equals(vo.getBankaffirm())) {
                                    errnum = "errnum=3";
                                } else if (vo.getBankstation() == null || "".equals(vo.getBankstation())) {
                                    errnum = "errnum=4";
                                } else if (vo.getPayway() == null || vo.getPaybankdt().equals("") || vo.getPaybankdt().equals("0")) {
                                    errnum = "errnum=5";
                                }
                                if (!"".equals(errnum)) {
                                    return new BaseResult(ErrorCodeEnum.PARAM_ERR);
                                } else {
                                    setPayInfo(vo);
                                    illegalactivityinfoMapper.updateIsbankaffirm(vo.getIaiid());
                                }
                            } else {
                                return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "其他冲销成功,超时冲销失败");
                            }
                        }
                    }
                }

            } catch (Exception e) {
                return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
            }

        } else {
            return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "用户信息验证失败");
        }
            return  new BaseResult();
    }
//导出

    public void illageExport(List<String> billids, HttpServletResponse response) {
        List<IllegalactivityinfoVO> illegalactivityinfoVOS = illegalactivityinfoMapper.findIllagelactivityInfo(billids);
        String[] headers = {"处罚书编号", "当事人", "驾驶证", "处罚交警大队代码", "金额", "滞纳金", "代理银行id", "银行名称", "账户名称", "账户", "是否分成", "处罚地自留金额", "采集地交警大队代码", "采集地行政区划", "区划代码", "区划名称", "采集地分成金额", "银行收款时间", "网点", "流水号", "付款方式", "信息状态", "专用票据编号", "发送时间", "是否异地", "是否开票", "状态", "核心流水号", "发送状态"};
        String[] col = {"billnum", "occurname", "certificatenum", "trafficunitnum", "funds", "latefee", "bankid", "payeebankname", "payeeaccountname", "payeeaccountcode", "isscale", "remainfunds", "collectunitnum", "collectcantonid", "collectcantonname", "collectcantonname", "collectfunds", "'paybankdt", "bankstation", "bankaffirm", "payway", "", "specialbillnum", "sendtime", "isnohere", "isspecialbill", "billstate", "hxbankaffirm", "issend"};
        ExportSXSSFUtil ex = new ExportSXSSFUtil();
        SXSSFWorkbook workbook = ex.exportExcelSXSSF("交警罚没列表", headers, col, illegalactivityinfoVOS, null);
        response.setContentType("application/vnd.ms-excel");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    new String(("交罚决定书单据.xls").getBytes(), "iso-8859-1"));
            OutputStream ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            logger.info("导出失败：" + e.toString());
        }

    }

    public BaseResult illegalactivitypayview(IllegalactivityinfoVO vo, UserVO user) {
        try {
            CommBankService cbs = new CommBankService();

            Map<String, String> rtnBank = cbs.processIllegalactivityPay();
            BankStationVO bankStationVO = baseDataMapper.getBankStation(user.getBankStationId());
            vo.setBankstation(bankStationVO.getBankstationcode());
            vo.setPaybankdt(rtnBank.get("hx_paybankdt"));
            vo.setBankaffirm(rtnBank.get("hx_bankaffirm"));
            vo.setIsspecialbill(0);
            vo.setIsnohere(0);
            vo.setSpecialbillnum(rtnBank.get("hx_bankaffirm"));
            BaseResult result = setPayInfo(vo);
            if (result.isSuccess()) {
                illegalactivityinfoMapper.updateIllegalactivityHxBankaffirm(vo.getBillnum(), rtnBank.get("hx_bankaffirm"));
            }
            return result;
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR.getCode(), "票据处理异常");
        }
    }
}
